<?php

/**
 * @author juanma
 * @copyright 2012
 */



class Sgit_Controller_Action extends Zend_Controller_Action
{

    protected $_main_model;
    protected $_main_form;
    protected $_checkZona = false;
    protected $_checkAcceso = true;
    protected $_checkSession = true;
    protected $_id_tablesorter = 'myTable';
    protected $_cache = null;
    protected $_idZona = null;
    protected $_auth = null;
    protected $_sgit_session = null;
    protected $_profiler = true;
    protected $_template = 'form';
    protected $_setParams = array();
    
    protected $_action_noacl = array('denied', 'register','excel','pdf');
    


    /**
     * Sgit_Controller_Action::init()
     * 
     * @return
     */
    public function init()
    {
        if($this->_setParams)
        {
            foreach($this->_setParams as $key => $value){
                $this->setParam($key,$value);
            }
        }

        if ($this->_profiler)
        {
            $db = Zend_Registry::get("database");
            $db->getProfiler()->setEnabled(true);
        }



        //aqui guardamos todas los modelos instanciados
        $this->_model = new stdClass();
        //aqui guardamos todas los formularios instanciados
        $this->_form = new stdClass();
        //aqui guardamos form elements
        $this->_element = new stdClass();


        //guardamos modelos precargados
        if ($this->_main_model)
        {
            $model = 'Application_Model_' . $this->_main_model;
            $this->_model->default = new $model();
        }


        //creo una serie de variables utiles tanbto en el action como en la vista
        $this->_actionName = $this->getRequest()->getActionName();
        $this->_controllerName = $this->getRequest()->getControllerName();
        $this->view->id_tablesorter = $this->_id_tablesorter;
        $this->view->actionName = $this->_actionName;
        $this->view->controllerName = $this->_controllerName;


        //comprueba si esta autenticado
        $this->_auth();



        //comprueba si se necesita zona y setea las variable de zonas
        $this->_zona();

        //comprueba que tiene permiso para realizar esta accion
        $this->_acl();

        //carga zend navigation y usa los herlper breadcrubms y pone el title
        $this->_navigation();

        //para inicilaizar cosas en hijos
        $this->_begin();


    }
    
    
     /**
     * Esta funcion sirve para inicializar las busquedas y valores del filtro
     * colocar simpre antes de las llamadas a los form_element
     */
    
    protected function setParam($key,$value)
    {
        if(!$this->_request->has($key)) 
            $this->_request->setQuery($key,$value);
    }
    
    
    
    protected function filterParams()
    {
        $params=array_merge($this->_request->getParams(),$this->_request->getQuery(),$this->_request->getPost());
        unset($params['controller'],$params['action'],$params['module']);
        return $params;
    }
    
    protected function hasFilterParams()
    {
        $parasm=$this->filterParams();
        $hasFilterParams=empty($parasm) ? false : true;
        $this->view->hasFilterParams=$hasFilterParams;
        return $hasFilterParams;
    }
    
  

    /**
     * Esta funcion es para reemplazar el init Zend_Controller_Action
     * 
     */
    protected function _begin()
    {
    }


    /**
     * acceso rapido para obtener los datacenters
     * devuelve las zoans y crea la variable de vista zonas 
     */
    protected function _getNombreZona($id)
    {
        return Sgit_Util_Zona::run($id);
    }




    /**
     * Sgit_Controller_Action::_getZonas()
     * Solo datacenters dc=1
     * @return
     */
    protected function _getZonas()
    {
        $this->_loadModel('Datacenter');
        
        $this->view->zonas= $this->_model->Datacenter->getAssoc('id','nombre',array('dc=?' => 1));
        

        
        return $this->view->zonas;
    }

    protected function _navigation()
    {
        
       
        
        if ($this->_checkSession)
        {
            
             //si es alguna de estas acciones no tratamos navigation
            if(in_array($this->_actionName,array('editar','insertar','borrar','denied', 'register','excel','pdf'))){
                return true;
            }
      
            
            if ($this->_auth->hasIdentity())
            {
                
                $pages = new Sgit_Navigation();
                $container = new Zend_Navigation($pages->toArray());
            
                $navigation = $this->view->navigation($container);
                
                //Esto hace que no salgan los titulo segun quien acceda
                // $navigation->setAcl($this->_acl);
                //$navigation->setRole($this->_auth->getIdentity()->id);

                $breadToTitle = $navigation->breadcrumbs()->render();
                
                if($breadToTitle) {
                    
                    $title = explode('&gt;', strip_tags($breadToTitle));
                    $title2= array_pop($title);
                    $title2=str_replace('&amp;','&',$title2);
                    
                    if(is_array($title)) $this->view->headTitle($title2);
                }
               
                
               
            }
        }

    }


    /**
     * Sgit_Controller_Action::indexAction()
     * Indice por defecto por si no esta definido mando a una pagina de no desarrollado
     * 
     * 
     * @return void
     */
    public function indexAction()
    {
        $this->view->headTitle('Page not developed');
        $this->_helper->viewRenderer->setNoRender(true);

        echo '<h1>Error</h1>
        <h2>Page not developed</h2>
        <p>You are trying to access an area not developed.</p>';

    }

    /**
     * Sgit_Controller_Action::deniedAction()
     * Pagina para el acceso denegado
     * 
     * @return void
     */
    final public function deniedAction()
    {
    }


    /**
     * Sgit_Controller_Action::registerAction()
     * 
     * Esta funcion registra todos los action en la lista de recursos ACL
     * @return void
     */
    final public function registerAction()
    {


        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $this->_updateAcl();
        $this->_acl = $this->_getAcl();

        if ($this->_checkZona)
        {
            $zonas = $this->_getZonas();

            foreach ($zonas as $k => $idZona)
            {
                $this->_register($k);
            }
        } else
        {
            $this->_register();
        }


        $this->_acl = $this->_setAcl($this->_acl);

        $param = array('idZona' => $this->_idZona);

        if ($this->_checkZona)
            $this->_helper->redirector->gotoSimple('index', $this->_controllerName, null, $param);
        else
            $this->_helper->redirector->gotoSimple('index', $this->_controllerName);


    }


    protected function _register($idZona = null)
    {

        $this->_loadModel('Datacenter');
        $this->_loadModel('AclResources');


        $codZona = is_numeric($idZona) ? ':' . $idZona : '';

        $key_parent = strtolower($this->_controllerName . $codZona);

        $zona = $this->_model->Datacenter->getNombreZona($idZona);

        $row_padre = $this->_model->AclResources->getRow(array('resource = ?' => $key_parent));

        if (!$row_padre)
        {
            $this->_model->AclResources->insert(array('resource' => $key_parent, 'notas' => 'Todas las acciones de ' . $this->_controllerName . ' ' . $zona));
        }

        //sino hay recurso padre se crea
        if (!$this->_acl->has($key_parent))
        {
            $this->_acl->add(new Zend_Acl_Resource($key_parent));
        }

        foreach (get_class_methods($this) as $v)
        {
            //estas acciones no se registran
            //pdfAction y excelAction pasan por indexAction con un forward
            
            $action = str_replace('Action', '', $v);
            
            if (in_array($action, $this->_action_noacl ))
                continue;

            if (strpos($v, 'Action'))
            {

                $check_auth = 1;
                $notas = null;

                switch ($action)
                {
                    case 'index':
                        $notas = 'Página principal de ' . $this->_controllerName . ' ' . $zona;
                        break;
                    case 'editar':
                        $notas = 'Editar ' . $this->_controllerName . ' ' . $zona;
                        break;
                    case 'insertar':
                        $notas = 'Insertar ' . $this->_controllerName . ' ' . $zona;
                        break;
                    case 'borrar':
                        $notas = 'Borrar ' . $this->_controllerName . ' ' . $zona;
                        break;
                    case 'autocomplete':
                        $check_auth = 0;
                        break;
                }


                $key_resource = strtolower($this->_controllerName . ':' . $action . $codZona);
                $row = $this->_model->AclResources->getRow(array('resource = ?' => $key_resource));


                if (!$row)
                {
                    $this->_model->AclResources->insert(array('resource' => $key_resource, 'parent' => $key_parent, 'notas' => $notas, 'check_auth' => $check_auth));
                }


                if (!$this->_acl->has($key_resource))
                {
                    $this->_acl->add(new Zend_Acl_Resource($key_resource));
                }
            }
        }
        return true;
    }


    /**
     * Sgit_Controller_Action::_auth()
     * 
     * @return
     */
    protected function _auth()
    {

        if ($this->_checkSession)
        {
            $this->_auth = Zend_Auth::getInstance();
            $this->view->auth = $this->_auth->getIdentity();
            $this->_sgit_session = Zend_Registry::get('sgit_session');


            $uri = $this->_request->getRequestUri();

            if (!$this->_auth->hasIdentity())
            {
                // Si el Usuario no esta identificado y no se dirige a la página de Login
                if ($this->_controllerName != 'login')
                {
                    // redireccionamos a login
                    $destino = base64_encode(urlencode($uri));
                    $this->_helper->redirector->gotoSimple('index', 'login', null, array('destino' => $destino));
                }
            }
        }
    }


    /**
     * Sgit_Controller_Action::_zona()
     * 
     * @return
     */
    protected function _zona()
    {
                
        //si se precisa zona
        if ($this->_checkZona)
        {

            $this->_idZona = $this->_request->getParam('idZona');

            if ($this->_idZona)
            {
                $this->_loadModel('Datacenter');
                
                $this->view->idZona = $this->_idZona;
                $this->zona = $this->_model->Datacenter->cacheAssoc($this->_idZona, 'nombre');
                $this->view->zona = $this->view->translate($this->zona);
                
                
                $datacenter = new Sgit_Form_Element_Select_Datacenter('idZona', array('firstBlank' => false));
                $datacenter->setLabel('');
                $datacenter->setAttrib('onchange', "irazona({$this->_idZona},this.value)");
                $datacenter->setValue($this->_idZona);
                $datacenter->setDecorators(array('ViewHelper', array(array('data' => 'HtmlTag'), array('tag' => 'span', 'class' => 'changedc')), ));


                if(in_array($this->_idZona,array_keys($datacenter->getMultiOptions()))){
                    $this->view->formchangeDC = $datacenter;
                }

                


                if (!$this->zona)
                {
                    throw new Zend_Controller_Exception(sprintf('The required Datacenter do not exits for %s', $this->_controllerName . ':' . $this->_actionName));
                }

            } else
            {
                throw new Zend_Controller_Exception(sprintf('Datacenter is required for %s', $this->_controllerName . ':' . $this->_actionName));
            }
        }
    }


    /**
     * Sgit_Controller_Action::_borrar()
     * 
     * @return
     */
    protected function _borrar($id='',$exit=true)
    {
        if(!$id){
            $id = $this->_getParam('id');
        }

        $n = $this->_model->default->deleteRow($id);
        $this->_afterBorrar();
        $this->_afterExecute();


        if($this->_file_upload){
            foreach($this->_file_upload as $filepload){
                Sgit_Util_removeFiles::run($filepload['tabla'],$filepload['key'],$id,'delete');
            }
        }

        //para que se registre en el profiler sino json corta y no llega a postDipatch
        $this->postDispatch(); 
        
        
        if($exit) {
            $json['status'] = is_numeric($n) ? 'ok' : 'ko';
            $this->_helper->json($json);
        }
        
        return $n;
    }




    protected function _reload(){
        $this->_reload=true;
    }
    protected function _close(){
        $this->_close=true;
    }
    
    
    /**
     * Sgit_Controller_Action::_editar()
     * 
     * @return
     * 
     */
    protected function _editar()
    {

        //carga formulario desde $this->_main_form

        $this->_loadForm();
 
      
      
      
      
      
        if (!$this->_id)
            $this->_id = $this->_getParam('id');


        if(!$_FILES){
            if (!$this->getRequest()->isXmlHttpRequest())
            {
                throw new Zend_Controller_Exception($this->_controllerName . ':' . $this->_actionName . ":{$this->_id} > Solo se puede acceder via ajax");
            }
        }


        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);


        $this->view->form = $this->_form;
        $this->view->id = $this->_id;

        if ($this->_request->isPost())
        {

            if (!$this->_form->isValid($this->getRequest()->getPost()))
            {
                echo $this->render($this->_template);
            } else
            {
                //editar
                //update campos
                
                //esta funcion update en db
                $this->_executeEditar();
                
                 //para subir el archivo solo si hay archivo y se define $this->_file_upload[$n]
                if($this->_file_upload)
                {
                    foreach($this->_file_upload as $k => $f){
                      if($_FILES[$this->_file_upload[$k]['key']]['error']==0) $this->_fileUpload($k,$this->_id);
                    }
                }
                
                
                
                
                //para realizar tareas tras update db
                $this->_afterEdit();
                //para realizar tareas tras update o insert db
                $this->_afterAddEdit();
                //para realizar tareas tras update
                $this->_afterExecute();
                
                
               
                

                if ($this->_reload)
                {
                    $json['status'] = 'reload';
                }elseif ($this->_close)
                {
                    $json['status'] = 'close';
                } 
                else
                {
                    //get fila por defecto llama a getRow pero puede llamar pj a get Proyecto o cualquiera
                    $row = $this->_getFila($this->_id);
                    
                    $json['status'] = 'ok';
                    $json['fila'] = $this->view->partial($this->_controllerName . '/fila.phtml', $row);
                }

                $this->postDispatch(); //para que se registre en el profiler sino json corta y no llega a postDipatch
                $this->_helper->json($json);

            }
        } else
        {

            $row = $this->_model->default->getRow($this->_id);
            //prepara los valore para insertarlos en la vista formulario
            $row = $this->_prepareValuesToForm($row);
            $this->_form->populate($row);
            echo $this->render($this->_template);

        }
    }

    protected function _fileUpload($n,$id)
    {



        $tabla=$this->_file_upload[$n]['tabla'];
        $name=$this->_file_upload[$n]['name'];
        $key=$this->_file_upload[$n]['key'];
        $dir=$this->_file_upload[$n]['dir'].DS.$id;;
 
        $adapter =  $this->_form->$name->getTransferAdapter();


        foreach ($adapter->getFileInfo() as $file => $info) {
            

            if($info['error']!=4){
                if(!file_exists(PUBLIC_DOCUMENT."/$tabla")) mkdir (PUBLIC_DOCUMENT."/$tabla");
                if(!file_exists(PUBLIC_DOCUMENT."/$tabla/$key")) mkdir (PUBLIC_DOCUMENT."/$tabla/$key");
                if(!file_exists($dir)) mkdir ($dir);
            }
            
            $newNameFile=$dir .DS .utf8_decode($info['name']);

            $adapter->addFilter('Rename',
                       array('target' => $newNameFile,
                             'overwrite' => true),$file);
                
            $adapter->receive($file);

        }
        
        
        
        
    }
    
    
    
    
    protected function _loadForm($main_form='',$template='form'){
        if($main_form) $this->_main_form=$main_form;
        
        $formulario='Application_Form_'. $this->_main_form;
        if (!$this->_form instanceof $formulario)
        {
            $this->_form = new $formulario();
        }
        
        $this->_template = $template;
    }

    

    /**
     * Sgit_Controller_Action::_insertar()
     * 
     * @return
     */
    protected function _insertar()
    {
        
        $this->_loadForm();
                

        $this->view->form = $this->_form;

        
        if(!$_FILES){
            if (!$this->getRequest()->isXmlHttpRequest())
            {
                throw new Zend_Controller_Exception($this->_controllerName . ':' . $this->_actionName . ' Only AJAX');
    
            }
        }


        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);



        //La primera peticion se hace via get, la segunda cuando se procesan los datos via post
        if ($this->getRequest()->isPost())
        {
            if (!$this->_form->isValid($this->getRequest()->getPost()))
            {
                echo $this->render($this->_template);
            } else
            {
                //insertar

                //añadir campos
                $id=$this->_executeInsertar();
                
                //para subir el archivo solo si hay archivo y se define $this->_file_upload[$n]
                if($this->_file_upload)
                {
                    foreach($this->_file_upload as $k => $f){
                        if($_FILES[$this->_file_upload[$k]['key']]['error']==0) $this->_fileUpload($k,$id);
                    }
                  
                }
                
                
                $this->_afterAdd();
                $this->_afterAddEdit();
                $this->_afterExecute();        
                        

                     
                if ($this->_reload)
                {
                    $json['status'] = 'reload';
                } else
                {
                    $row = $this->_getFila($this->_id);
                    $json['status'] = 'ok';
                    $json['fila'] = $this->view->partial($this->_controllerName . '/fila.phtml', $row);
                }


                $this->postDispatch(); //para que se registre en el profiler sino json corta y no llega a postDipatch
                $this->_helper->json($json);


            }
        } else
        {
            
            $row = $this->_prepareValuesToForm((array )$row);
            
            
            $this->_form->populate($row);
            echo $this->render($this->_template);
            

        }

    }




    /**
     * Sgit_Controller_Action::_autocomplete()
     * 
     * @return
     */
    protected function _autocomplete($model = null, $col = null)
    {
        //$this->_helper->layout->disableLayout();
        //$this->_helper->viewRenderer->setNoRender(true);

        $term = $this->_request->getParam('term');
        $col = is_null($col) ? $this->_request->getParam('col') : $col;
        $idZona = $this->_request->getParam('idZona', null);
        $where = ($idZona) ? array('id_zona = ?' => $idZona) : null;


        if (is_null($model))
        {
            $cols = $this->_model->default->autocomplete($term, $col, $where);
        } else
        {
            $cols = $model->autocomplete($term, $col, $where);
        }

        $this->postDispatch(); //para que se registre en el profiler sino json corta y no llega a postDipatch

        $this->_helper->json($cols);

    }


    protected function _getJson()
    {
        $id = $this->_request->getParam('id');
        $col = $this->_request->getParam('col');


        $row = $this->_model->default->getRow($id);

        $this->postDispatch(); //para que se registre en el profiler sino json corta y no llega a postDipatch
        if ($col)
            $this->_helper->json(array($col => $row[$col]));
        else
            $this->_helper->json($row);

    }


    /**
    *
    *Funciones para realziar tareas despues de accion DB
    *
    */
    protected function _afterAdd(){}
    protected function _afterEdit(){}
    protected function _afterBorrar() {}
    protected function _afterAddEdit(){}
    protected function _afterExecute(){}
    
    


    /**
     * Sgit_Controller_Action::execute()
     * Esta es la funcion que actualiza valor en DB
     * @return
     */

    protected function _executeEditar()
    {
        if (!$this->_id)
            throw new Zend_Controller_Exception("Es necesario el identificador de fila en el metodo executeEditar");

        $data = $this->_prepareValuesToDb();
        $this->_model->default->updateRow($data, $this->_id);
        return $this->_id;
    }
   
    
    

    protected function _executeInsertar()
    {
        $data = $this->_prepareValuesToDb();
        $this->_id = $this->_model->default->insertRow($data);

        if (!$this->_id)
            throw new Zend_Controller_Exception("Es necesario que se devuelva identificador de fila en el metodo executeInserar");

        return $this->_id;
    }
    
    

    /**
     * Sgit_Controller_Action::prepareRowsToTr()
     * 
     * @return
     */
    protected function _prepareRowsToTr($rows, $aColumns = array())
    {
        foreach ((array)$rows as $row)
        {
            $row = $this->_prepareValuesToTr($row);
            //para tenerlo disponible en el partialLoop
            if ($this->_idZona)
                $row['idZona'] = $this->_idZona;
            $newrows[] = $row;
        }
        return $newrows;
    }


    /**
     * Sgit_Controller_Action::prepareValuesToForm()
     * 
     * @return
     */
    protected function _prepareValuesToForm($row)
    {
        return $row;
    }
    

    

    /**
     * Sgit_Controller_Action::prepareValuesToTr()
     * 
     * @return
     */
    protected function _prepareValuesToTr($row)
    {
        return $row;
    }

    /**
     * Sgit_Controller_Action::prepareValuesToDb()
     * 
     * @return
     */
    protected function _prepareValuesToDb()
    {
        return $this->_form->getValues();
    }
    
    
    
    
    
    /**
     * Esta funcion llama al formateador de fila tras un insert, edit
     * Sgit_Controller_Action::getFila()
     * 
     * Devuelve una fila TR formateada
     * @return
     */
    protected function _getFila($id)
    {

        $row = $this->_model->default->getRow($id);
        $row = $this->_prepareValuesToTr($row);
        return $row;
    }

    /**
     * Sgit_Controller_Action::getValueFromFormElement()
     * 
     * @return
     */
    protected function _getValueFromFormElement($element, $key)
    {
        if ($key)
        {
            $select = $this->_model->default->$element();
            return $select->getMultiOption($key);
        } else
        {
            return '';
        }

    }


    protected function _acl()
    {

        if ($this->_checkSession)
        {

            if (in_array($this->_actionName, $this->_action_noacl))
                return true;

            $this->_acl = $this->_getAcl();

            if (is_numeric($this->_idZona))
                $codZona = ':' . $this->_idZona;
            else
                $codZona = '';


            $key_resource = strtolower($this->_controllerName . ':' . $this->_actionName . $codZona);
            $key_parent = strtolower($this->_controllerName . $codZona);


            $id_usuario = $this->_auth->getIdentity()->id;

            //permite acceso en funcion de Sgit_Acl_Assert_Check
            $this->_acl->allow(null, null, null, new Sgit_Acl_Assert_Check($this->_checkAcceso));


            if (!$this->_acl->has($key_resource))
            {
                //print ' No existe recurso ' . $key_resource;
                return true;
            }


            if (!$this->_acl->isAllowed($id_usuario, $key_resource))
            {

                if ($this->_request->isXmlHttpRequest())
                {
                    $this->_helper->layout->disableLayout();
                }


                $this->_request->setControllerName('error');
                $this->_request->setActionName('denied');


            }

            return true;
        }

    }


    /**
     * Sgit_Controller_Action::_getCache()
     * 
     * @return
     */
    protected function _getCache()
    {
        if (null === $this->_cache)
        {
            $this->_cache = $this->getInvokeArg('bootstrap')->getResource('Cache');
        }
        return $this->_cache;
    }


    protected function _getAcl()
    {
        $this->_cache = $this->_getCache();

        if (!$acl = $this->_cache->load('acl'))
        {
            $acl = new Sgit_Acl();
            $this->_cache->save($acl, 'acl');
        }

        return $acl;
    }

    protected function _setAcl($acl)
    {
        $this->_cache = $this->_getCache();
        $this->_cache->remove('acl');
        $this->_cache->save($acl, 'acl');
        return $acl;
    }

    protected function _updateAcl()
    {
        $this->_cache = $this->_getCache();
        $this->_cache->remove('acl');
        $acl = new Sgit_Acl();
        $this->_cache->save($acl, 'acl');
        return $acl;
    }


    protected function _getFiltrosValues($filtros)
    {
        
        $values = array();
        if ($this->_request->isPost())
        {
            if ($filtros->isValid($this->getRequest()->getPost()))
            {
                $values = $filtros->getValues();
            }
        }else{
            $values=$this->getRequest()->getParams();
        }

        
        return $values;
    }


    protected function _loadModel($model)
    {
        $modelo = 'Application_Model_' . $model;
        if (!$this->_model->$model instanceof $modelo)
        {
            $this->_model->$model = new $modelo();
        }
    }


    function postDispatch()
    {

        $this->_logger = Zend_Registry::get('loggerTxt');

        try
        {
            if ($this->_profiler == true)
            {
                $db = Zend_Registry::get("database");

                $profiler = $db->getProfiler();

                $i = 0;

                if ($profiler->getTotalNumQueries())
                {
                    foreach ($profiler->getQueryProfiles() as $query)
                    {
                        if ($query->getQueryType() == 1)
                            continue;

                        $data[$i]['sql'] = $query->getQuery();
                        $data[$i]['time'] = round($query->getElapsedSecs(), 5);
                        $data[$i]['params'] = implode(' || ', $query->getQueryParams());
                        $data[$i]['session'] = session_id();
                        $data[$i]['fecha'] = date('Y-m-d H:i:s');
                        $data[$i]['model'] = $this->_controllerName . ':' . $this->_actionName;

                
                        if($this->_auth){
                        $nombre= $this->_auth->getIdentity()->nombre;
                        }

                        $format = str_pad($data[$i]['time'], 8) . str_pad($data[$i]['model'], 38) .  str_pad($nombre, 30)  . str_replace("\n", ' ', $data[$i]['sql']);
                        $this->_logger->info($format);
                        $i++;
                    }
                }
                /*
                $db->getProfiler()->setEnabled(false);
                
                $model = new Application_Model_Profiles();
                
                if(isset($data)){
                    foreach ((array )$data as $data)
                    {
                        $model->insert($data);
                    }
                }*/
                
            }
        }
        catch (exception $e)
        {
            echo $e->__toString();
        }


    }
    
    
    
    

     /**
     * Sgit_Controller_Action::_toExport()
     * Esta funcion redirige a pdf o excel en funcion de lo seleccionado
     * 
     * @return void
     */
    public function _toExport($return=false)
    {
        if($this->_hasParam('pdf_x') || $this->_hasParam('pdf_y') || $this->_hasParam('pdf'))
        {
            $this->_forward('pdf');
            if($return) return true;
        }
        if($this->_hasParam('excel_x') || $this->_hasParam('excel_y') || $this->_hasParam('excel'))
        {
            $this->_forward('excel');
            if($return) return true;
        }
    }
    /**
     * Sgit_Controller_Action::_getXml()
     * 
     * parsea el xml con los datos para la exportación pdf y excel
     * @return
     */
    public function _getXml(){
        
        
        $filexml=$this->view->getScriptPath($this->_controllerName.DS.$this->_actionName.'.xml');
        $xml = simplexml_load_file($filexml,"SimpleXMLElement",LIBXML_NOCDATA);
        
        $columnas=$xml->columnas->columna;
        $i=0;
        foreach($columnas as $col)
        {
             $excol[$i]['key'] =(string) $col->key['data'];
             $excol[$i]['header'] =(string) $col->header['data'];
             $excol[$i]['width'] =(string) $col->width['data'];
             if($col->resaltar_col['data']) $excol[$i]['resaltar_col'] =(bool)$col->resaltar_col['data'];
             $i++;
        }

        return $excol;
    }





}


?>